<?php

namespace think\wework\Api;

use think\Wework;
use think\facade\Cache;
use think\wework\Abstracts\WeworkApi;

class Bot extends WeworkApi
{
    private string $puppetToken;
    private static array $instance = [];
    public static function getInstance($token): Bot
    {
        if(empty(self::$instance[$token]) || !self::$instance[$token] instanceof Bot) {
            self::$instance[$token] = new self($token);
        }
        return self::$instance[$token];
    }

    public function __construct(string $token)
    {
        parent::__construct();
        $this->puppetToken = $token;
    }

    public function start(): bool
    {
        $redis = Cache::store('redis')->handler();
        $hashKey = strtoupper(md5($this->puppetToken));
        if(false !== $redis->lPush(Wework::BotTokenListKey,$this->puppetToken)) {
            while (true) {
                $data = $redis->hGet(Wework::BotTokenListHash, $hashKey);
                if(!empty($data)) {
                    $redis->hDel(Wework::BotTokenListHash, $hashKey);
                    break;
                }
                usleep(250000);
            }
            return $data;
        } else {
            return false;
        }
    }
}
